/**
 * Created by Janpoem on 2016/1/31 0031.
 */

const _ = require('underscore');

var caches = [];

var callFn = function (fn, obj, args) {
	if (typeof fn === 'function') {
		fn.apply(obj, args || []);
	}
};

var Cache = function (name, options) {
	if (!caches[name]) {
		this._name = name;
		this.data = {};
		this.index = {};
		this.options = {
			onload: null,
			life: 60 * 60 // 1小时
		};
		this.setOptions(options || {});
	}
	return caches[name];
};

Cache.call = callFn;

Cache.prototype.setOptions = function (options) {
	this.options = _.extend(this.options, options);
	return this;
};

Cache.prototype.load = function (name, fn) {
	if (name === '' || name === false || name === 'null' || typeof name === 'undefined') {
		//console.log('cache ' + name + ' invalid key');
		callFn(fn, this, [name, false]);
	}
	else {
		if (this.data[name] && this.data[name] !== false) {
			var expire = new Date(this.data[name].update.getTime());
			expire.setSeconds(expire.getSeconds() + this.options.life);
			var now = new Date();
			if (now.getTime() < expire.getTime()) {
				//console.log('cache ' + name + ' hit, life ' + parseInt((expire.getTime() - now.getTime()) / 1000) + ' second');
				callFn(fn, this, [name, this.data[name].data]);
				return this;
			}
		}
		//console.log('cache ' + name + ' load');
		callFn(this.options.onload, this, [name, fn]);
	}
	return this;
};

Cache.prototype.save = function (name, data) {
	if (data === false)
		this.data[name] = false;
	else {
		this.data[name] = {
			name: name,
			data: data,
			update: new Date()
		};
	}
	return this;
};

module.exports = Cache;